<script setup lang="ts">
import { DatePickerInstance } from 'element-plus'
import type { FormItemTool } from '../../../types/index.ts'
import dayjs from 'dayjs'
import {useShortcuts} from './useShortcuts'

type IProps = {
  item: FormItemTool<'datepicker'>
  allDisabled?: boolean
  isEditByRow: boolean
  data: Record<string, any>
}
const { item, allDisabled, isEditByRow, data } = defineProps<IProps>()
const emit = defineEmits(['update:data'])
const value = defineModel<any>('value')

const shortcuts = useShortcuts(item)

const startKey = computed(() => {
  if(item.config?.mapping) return item.config.mapping['start']
  return undefined
})
const endKey = computed(() => {
  if(item.config?.mapping) return item.config.mapping['end']
  return undefined
})

const modelValue = computed({
  get: () => {
    if(startKey.value && endKey.value && item.config?.type === 'daterange') {
      return [data?.[startKey.value], data?.[endKey.value]]
    }
    return value.value
  },
  set: (val) => {
    if(startKey.value && endKey.value && item.config?.type === 'daterange') {
      console.log('Setting date range:', val);
      const dataScoped = { ...data }
      dataScoped[startKey.value] = val?.[0]
      dataScoped[endKey.value] = val?.[1]
      emit('update:data', dataScoped)
    }else {
      value.value = val
    }
  },
})
// 不使用泛型有的方法会拿不到，目前不知道为什么
const elRef = useTemplateRef<DatePickerInstance>('elRef')
const getRef = () => {
  return elRef.value
}
defineExpose({
  getRef,
})
</script>
<template>
<span class="w-full">
  <el-date-picker
    v-if="isEditByRow"
    ref="elRef"
    :disabled="allDisabled"
    v-model="modelValue"
    :valueFormat="`YYYY-MM-DD${item.config?.type?.includes('time') ? ' HH:mm:ss' : ''}`"
    :format="`YYYY/MM/DD${item.config?.type?.includes('time') ? ' HH:mm:ss' : ''}`"
    style="width: 100%;"
    :shortcuts="shortcuts"
    v-bind="item.config"
    v-on="item.eventFunction || {}"
  >
    <template v-for="slotName in item.slotNames" #[slotName]="slotData">
      <slot :name="slotName" :slotData="slotData"> </slot>
    </template>
  </el-date-picker>
  <span v-else> {{ dayjs(value).format(item.config?.format || 'YYYY-MM-DD') ?? value }} </span>
</span>
</template>

<style scoped lang="scss"></style>
